<script setup>
import { ref } from 'vue';
import MyTable from '@/components/MyTable.vue';
import { deleteProjects, getProjectListApi, insertProject, modifyProject,searchProject } from '@/api/project';
import { ElMessage, ElMessageBox } from 'element-plus';
import { emailValid } from '@/utils/validator';
getProjectList(10,1)
// 表单数据
const data = ref([])
const projectCount = ref(0)
//控制弹窗
const dialogVisible = ref(false)
// 弹窗组件实例
const formRef = ref(null)
// 弹窗表单响应式数据
const dialogFormData = ref({
  "projectId": "",
  "companyName": "",
  "groupName": "",
  "systemName": "JES",
  "contactPerson": "",
  "contactEmail": '',
  "hourlyRate": '',
  "contractHours": '',
  "commitmentHours": '',
  "consumedHours": '',
  "remainingHours": '',
  "remainingCost": ''
})

const MyFormRef = ref(null)
const keyword = ref("")

//表单label
const labels = ref([
  {key:'项目号',value:'projectId'},
  {key:'企业名称',value:'companyName'},
  {key:'所属集团',value:'groupName'},
  {key:'体系名称',value:'systemName'},
  {key:'工时单价(元)',value:'hourlyRate'},
  {key:'合同总工时(天)',value:'contractHours'},
  {key:'合同承诺工时(天)',value:'commitmentHours'},
  {key:'联络人',value:'contactPerson'},
])
// 所属体系选择
const systemOptions = ref(
  [
    {value:'JES',key:1},
    {value:'SES',key:2},
    {value:'3FES',key:3},
    {value:'YLES',key:4},
  ]
)
// 弹窗标题
const currentDialogTitles = ref([
  {key:1,value:'修改项目'},
  {key:2,value:'查看项目'},
  {key:3,value:'创建项目'}
])
// 当前弹窗类型
const currentDialogTitleIndex = ref(0)
//查看数据
const handleShow = (id) => {
  dialogFormData.value = {...data.value.find((item) => {return item.id === id})}
  dialogVisible.value = true
  currentDialogTitleIndex.value = 1
  dialogFormData.value.consumedHours = 0;
  dialogFormData.value.remainingHours = dialogFormData.value.commitmentHours - 0;
  dialogFormData.value.remainingCost = dialogFormData.value.remainingHours * dialogFormData.value.hourlyRate
}
// 修改数据
const handleEdit = (id) => {
  dialogFormData.value = {...data.value.find((item) => {
    return item.id === id
  })}
  dialogVisible.value = true
  currentDialogTitleIndex.value = 0
}

// 删除数据
const handleDel = (id) => {
  const ids = [id]
  ElMessageBox.confirm('你确定要删除这条数据吗? 注意!此操作不可逆转')
    .then(async() => {
        try{
          await deleteProjects(ids)
          ElMessage.success("删除成功")
          await MyFormRef.value.getDataList()
        }catch(e) {
          ElMessage.error(e.message)
        }
    }).catch(()=>{

    })

}
// 弹窗关闭前
const handleDialogClose = () => {
  formRef.value.resetFields()
  dialogVisible.value = false
}
// 点击新增数据
const handleAdd = () => {
  dialogVisible.value = true
  currentDialogTitleIndex.value = 2
}
// 提交新增或修改数据
const handleSubmit = () => {
  formRef.value.validate(async (valid) => {
      if(!valid) {
        return ElMessage.error('请填写正确的信息')
      }
      if(currentDialogTitleIndex.value === 2) {
        //新增
        try{
          await insertProject(dialogFormData.value)
          ElMessage.success("新增项目成功")
          await MyFormRef.value.getDataList()
          dialogVisible.value = false
        }catch(e) {
          ElMessage.error(e.message)
        }
      }else {
        // 修改
        try{
          const changes =  getChangeFields()
          if(Object.keys(changes).length > 0) {
            changes.id = dialogFormData.value.id
            await modifyProject(changes)
            ElMessage.success('修改成功')
            await MyFormRef.value.getDataList()
            dialogVisible.value = false
          }else {
            ElMessage.info("没有修改任何数据")
          }
        }catch(e) {
          ElMessage.error(e.message)
        }
      }
    })
}

// 查询项目
const handleSearch = async () => {
  if(keyword.value === '') {
    ElMessage.error("请输入搜索关键字")
    return
  }
  const res = await searchProject(keyword.value)
  if(res.length === 0) {
    ElMessage.warning("查不到满足条件的用户")
  }else{
    data.value = res
    ElMessage.success('查询成功')
  }

}
// 得到被修改的字段
const getChangeFields = () => {
  const originalData = {...data.value.find((item) => {return item.id === dialogFormData.value.id})}


  const changes = {}
  for (const key in dialogFormData.value) {


    if(dialogFormData.value[key] !== originalData[key]) {

      changes[key] = dialogFormData.value[key]
    }
  }
  return changes
}
// 得到项目列表
async function getProjectList(pageSize,page) {
  try{
    const res = await getProjectListApi(pageSize,page)
    data.value = res.projectList
    projectCount.value = res.projectCount
  }catch(e) {
    ElMessage.error(e.message)
  }
}
// 表单校验
const validateField = {
  projectId: (rule, value, callback) => {
    if (!value) {
      callback(new Error('请输入项目号'));
    } else if (value.length > 50) {
      callback(new Error('项目号最大长度为50'));
    } else {
      callback();
    }
  },

  companyName: (rule, value, callback) => {
    if (!value) {
      callback(new Error('请输入企业名称'));
    } else if (value.length > 100) {
      callback(new Error('企业名称最大长度为100'));
    } else {
      callback();
    }
  },
  contactPerson: (rule, value, callback) => {
    if (!value) {
      callback(new Error('请输入联络人姓名'));
    } else if (value.length > 50) {
      callback(new Error('联络人姓名最大长度为50'));
    } else {
      callback();
    }
  },

  contactEmail: (rule, value, callback) => {
    if (!value) {
      callback(new Error('请输入联络人邮箱'));
    } else if (!emailValid(value)) {
      callback(new Error('请输入有效的邮箱地址'));
    } else {
      callback();
    }
  },


  hourlyRate: (rule, value, callback) => {
    if (value === undefined || value === null) {
      callback(new Error('请输入工时单价'));
    } else if (isNaN(value) || value <= 0) {
      callback(new Error('工时单价必须大于0'));
    } else {
      callback();
    }
  },

  contractHours: (rule, value, callback) => {
    if (value === undefined || value === null) {
      callback(new Error('请输入合同工时'));
    } else if (value % 0.5 !== 0) {
      callback(new Error('合同工时应为0.5天的倍数'));
    } else {
      callback();
    }
  },


  commitmentHours: (rule, value, callback) => {


    if (value === undefined || value === null) {
      callback(new Error('请输入合同承诺工时'));
    } else if (value <= 0) {
      callback(new Error('合同承诺工时必须大于0'));
    } else if (dialogFormData.value.contractHours != null
     && value < dialogFormData.value.contractHours ) {
      callback(new Error('合同承诺工时必须大于合同工时'));
    } else if (value % 0.5 !== 0) {
      callback(new Error('合同承诺工时应为0.5天的倍数'));
    } else {
      callback();
    }
  },
};

const dialogRules = {
  projectId: [
    { required: true, message: '请输入项目号', trigger: 'blur' },
    { validator: validateField.projectId, trigger: 'blur' }
  ],
  companyName: [
    { required: true, message: '请输入企业名称', trigger: 'blur' },
    { validator: validateField.companyName, trigger: 'blur' }
  ],
  groupName: [
    { required: true, message: '请输入所属集团', trigger: 'blur' },
    { validator: validateField.groupName, trigger: 'blur' }
  ],
  systemName: [
    { required: true, message: '请选择所属体系', trigger: 'blur' },
    { validator: validateField.systemName, trigger: 'blur' }
  ],
  contactPerson: [
    { required: true, message: '请输入联络人姓名', trigger: 'blur' },
    { validator: validateField.contactPerson, trigger: 'blur' }
  ],
  contactEmail: [
    { required: true, message: '请输入联络人邮箱', trigger: 'blur' },
    { validator: validateField.contactEmail, trigger: 'blur' }
  ],
  hourlyRate: [
    { required: true, message: '请输入工时单价', trigger: 'blur' },
    { validator: validateField.hourlyRate, trigger: 'blur' }
  ],
  contractHours: [
    { required: true, message: '请输入合同工时', trigger: 'blur' },
    { validator: validateField.contractHours, trigger: 'blur' }
  ],
  commitmentHours: [
    { required: true, message: '请输入合同承诺工时', trigger: 'blur' },
    { validator: validateField.commitmentHours, trigger: 'blur' }
  ]
};
</script>
<template>
    <div class="pj_base_container">
      <el-dialog :title="currentDialogTitles[currentDialogTitleIndex].value" v-model="dialogVisible" :before-close="handleDialogClose">
        <el-form ref="formRef" :model="dialogFormData" :rules="dialogRules" :disabled="currentDialogTitleIndex === 1">
          <el-form-item prop="projectId" style="width: 30%;"   label="项目号">
            <el-input v-model="dialogFormData.projectId" placeholder="" size="default" />
          </el-form-item>
          <el-form-item prop="companyName" style="width: 30%;"   label="企业名称">
            <el-input v-model="dialogFormData.companyName" placeholder="" size="default"  />
          </el-form-item>
          <el-form-item prop="groupName" style="width: 30%;"   label="所属集团">
            <el-input v-model="dialogFormData.groupName" placeholder="" size="default"   />
          </el-form-item>
          <el-form-item prop="systemName" style="width: 30%;"   label="所属体系">
            <el-select v-model="dialogFormData.systemName" size="default" placeholder="">
                <el-option v-for="item in systemOptions" :key="item.key" :label="item.label" :value="item.value">
                </el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="contactPerson" style="width: 30%;"   label="联络人">
            <el-input v-model="dialogFormData.contactPerson" placeholder="" size="default" />
          </el-form-item>
          <el-form-item prop="contactEmail" style="width: 30%;"   label="联络人邮箱">
            <el-input v-model="dialogFormData.contactEmail" placeholder="" size="default"  />
          </el-form-item>
          <el-form-item prop="hourlyRate" style="width: 30%;"   label="工时单价(元)">
            <el-input v-model="dialogFormData.hourlyRate" placeholder="" size="default"    />
          </el-form-item>
          <el-form-item prop="contractHours" style="width: 30%;"   label="合同工时(天)">
            <el-input v-model="dialogFormData.contractHours" placeholder="" size="default" />
          </el-form-item>
          <el-form-item prop="commitmentHours" style="width: 30%;"   label="合同承诺工时(天)">
            <el-input v-model="dialogFormData.commitmentHours" placeholder="" size="default"/>
          </el-form-item>
          <el-form-item prop="consumedHours" style="width: 30%;"   label="已消耗工时(天)" v-if="currentDialogTitleIndex === 1">
            <el-input v-model="dialogFormData.consumedHours" placeholder="" size="default" disabled/>
          </el-form-item>
          <el-form-item prop="remainingHours" style="width: 30%;"   label="剩余工时(天)" v-if="currentDialogTitleIndex === 1">
            <el-input v-model="dialogFormData.remainingHours" placeholder="" size="default" disabled/>
          </el-form-item>
          <el-form-item prop="remainingCost" style="width: 30%;"   label="剩余费用(元)" v-if="currentDialogTitleIndex === 1">
            <el-input v-model="dialogFormData.remainingCost" placeholder="" size="default" disabled />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer" >
            <el-button @click="handleDialogClose()" size="default" v-if="currentDialogTitleIndex !== 1">取消</el-button>
            <el-button type="primary" @click="handleSubmit" size="default" v-if="currentDialogTitleIndex !== 1">
              确定
            </el-button>
          </div>
        </template>
      </el-dialog>
      <div class="title" >
        <h3>项目基础信息管理</h3>
      </div>
      <div class="inp" style="margin-bottom: 20px;">
        <div class="left">
          <el-input  placeholder="请输入项目号/企业/集团/联络人" size="default" v-model.trim="keyword"></el-input>
          <el-button type="primary"  size="default" @click="handleSearch">查询</el-button>
        </div>
        <div class="right">
          <el-button type="primary" circle  size="default"
          @click="handleAdd"><el-icon><Plus /></el-icon></el-button>
        </div>
      </div>
      <MyTable :data="data" :labels="labels"
      @del="handleDel" @show="handleShow" @edit="handleEdit" :dataCount="projectCount" :paging="true"
      :op="true" :select="false" ref="MyFormRef"
      @getDataList="getProjectList"></MyTable>
    </div>
</template>

<style lang="less" scoped>
.pj_base_container {
  background-color: #fff;
  padding: 20px 40px;
  .title {
    h3 {
      font-weight: normal;
    }
  }
  .inp {
    margin-top: 20px;
    display: flex;
    justify-content: space-between;
    .left {
      display: flex;
      width: 30%;
      .el-button {
        margin-left: 20px;
      }
    }
    .right {
      display: flex;
      justify-content: center;
      align-items: center;
    }
  }
}
::v-deep .el-table {
  .el-button {
    border: none;
    font-size: 20px;
    background-color: transparent;
  }
}
::v-deep .el-form {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}
::v-deep   .el-form-item  {
    display: block;
    width: 45%;
  }

  ::v-deep .el-form-item__label {
    color: black;
    font-size: 14px;
    margin-bottom: 5px;
  }
</style>
